package com.zby.filter.util;

import com.zby.filter.util.core.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created By zby on 16:51 2019/1/30
 */

public class PropertyUtil {

    private static Logger logger = LoggerFactory.getLogger(PropertyUtil.class);

    /**
     * Created By zby on 20:28 2019/2/13
     *
     * @param bean  实体对象
     * @param props 属性名称
     */
    public static Object getProperty(Object bean, String props) {
        if (bean == null)
            throw new RuntimeException("实例化对象不存在bean=" + bean);
        if (StringHelper.isBlank(props))
            throw new RuntimeException("属性名称不存在props=" + props);
        Class<?> clazz = null;
        String methodName = null;
        String fieldName = null;
        String typeName = null;
        try {
            clazz = bean.getClass();
            if (props.indexOf(".") != -1) {
                methodName = MethodHelper.propsToGetMethod(props.substring(0, props.indexOf(".")));
                Method method = clazz.getDeclaredMethod(methodName);
                Object obj = method.invoke(bean);
                return getProperty(obj, props.substring(props.indexOf(".") + 1));
            }
            Field field = clazz.getDeclaredField(props);
            typeName = field.getType().getName();
            if (typeName.equalsIgnoreCase("boolean")) {
                field.setAccessible(true);
                return field.getBoolean(bean);
            }

            methodName = MethodHelper.propsToGetMethod(props);
            Method method = clazz.getDeclaredMethod(methodName);
            return method.invoke(bean);
        } catch (NoSuchMethodException e) {
            logger.error(clazz + "类型没有" + methodName + "方法");
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            logger.error(clazz + "类型没有" + fieldName + "属性");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
